﻿using Bricks.Business.Data.Repositories.ScheduleManagement;
using Bricks.Business.Models.ScheduleManagement;
using Bricks.Component.Utils;
using Bricks.Site.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;

namespace Bricks.Business.Service.Impl
{
    /// <summary>
    /// 涵洞统计服务实现
    /// </summary>
    [Export(typeof(ICulvertStatisticsService))]
    public class CulvertStatisticsService : ICulvertStatisticsService
    {
        [Import]
        protected ICulvertStatisticsRepository CulvertStatisticsRepository { get; set; }

        [Import]
        protected ICulvertStatisticsDetailRepository CulvertStatisticsDetailRepository { get; set; }

        public IQueryable<CulvertStatistics> CulvertStatisticses
        {
            get { return CulvertStatisticsRepository.Entities; }
        }

        public IQueryable<CulvertStatisticsDetail> CulvertStatisticsDetails
        {
            get { return CulvertStatisticsDetailRepository.Entities; }
        }

        /// <summary>
        /// 获取涵洞统计列表
        /// </summary>
        /// <param name="projectID"></param>
        /// <param name="contractID"></param>
        /// <returns></returns>
        public List<CulvertStatisticsView> GetCulvertTotalList(Guid projectID, Guid contractID)
        {
            List<CulvertStatisticsView> result = new List<CulvertStatisticsView>();
            var dataList = CulvertStatisticses.Where(m => m.ProjectID == projectID && m.ContractID == contractID).OrderByDescending(m => m.AddDate);
            if (dataList != null && dataList.Count() > 0)
            {
                CulvertStatisticsView record;
                foreach (CulvertStatistics cs in dataList)
                {
                    record = new CulvertStatisticsView();
                    record.ID = cs.ID;
                    record.ProjectID = cs.ProjectID;
                    record.ContractID = cs.ContractID;
                    record.StatisticalCycle = cs.StatisticalCycle;

                    //明细过滤
                    var culvertStatisticsDetails = from m in CulvertStatisticsDetails
                                                   where m.CulvertStatisticsID == cs.ID
                                                   select m;

                    if (culvertStatisticsDetails != null && culvertStatisticsDetails.Count() > 0)
                    {
                        //汇总各个字段
                        record.LengthDesignTotal = culvertStatisticsDetails.Sum(m => m.LengthDesign);
                        record.LengthRealityTotal = culvertStatisticsDetails.Sum(m => m.LengthReality);
                        record.BasicProgressTotal = culvertStatisticsDetails.Sum(m => m.BasicProgress);
                        record.WallBodyProgressTotal = culvertStatisticsDetails.Sum(m => m.WallBodyProgress);
                        record.BlindFlangeProgressTotal = culvertStatisticsDetails.Sum(m => m.BlindFlangeProgress);
                        record.BackfillProgressTotal = culvertStatisticsDetails.Sum(m => m.BackfillProgress);
                        record.BuildingProgressTotal = culvertStatisticsDetails.Sum(m => m.BuildingProgress);

                        //因为可能为空，所以需要进行空判断后再计算
                        //实际
                        var lrt = record.LengthRealityTotal.HasValue ? record.LengthRealityTotal : 0;

                        //设计
                        var ldt = record.LengthDesignTotal.HasValue ? record.LengthDesignTotal : 0;

                        //总完成进度
                        decimal? countResult = 0;
                        if (ldt.HasValue && ldt.Value != 0)
                            countResult = (lrt / (ldt.Value));
                        if (countResult != null && countResult.HasValue)
                            record.TotalFinishedProgress = (countResult.Value * 100).ToString("F2") + "%";
                        else
                            record.TotalFinishedProgress = "0%";
                    }
                    result.Add(record);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取涵洞统计明细列表
        /// </summary>
        /// <param name="culvertID">涵洞ID</param>
        /// <param name="newCulvertID">新的涵洞ID（拷贝上月数据时使用）</param>
        /// <returns></returns>
        public List<CulvertStatisticsDetailView> GetCulvertDetailList(Guid culvertID, Guid newCulvertID)
        {
            List<CulvertStatisticsDetailView> result = new List<CulvertStatisticsDetailView>();
            var dataList = CulvertStatisticsDetails.Where(m => m.CulvertStatisticsID == culvertID);
            if (dataList != null && dataList.Count() > 0)
            {
                CulvertStatisticsDetailView record;
                foreach (CulvertStatisticsDetail detail in dataList)
                {
                    record = new CulvertStatisticsDetailView();
                    record = detail.CopyTo<CulvertStatisticsDetailView>();
                    if (!newCulvertID.Equals(Guid.Empty))
                        record.CulvertStatisticsID = newCulvertID;

                    //因为可能为空，所以需要进行空判断后再计算
                    //实际
                    var lr = detail.LengthReality.HasValue ? detail.LengthReality : 0;

                    //设计
                    var ld = detail.LengthDesign.HasValue ? detail.LengthDesign : 0;

                    decimal? countResult = 0;
                    if (ld.HasValue && ld.Value != 0)
                        countResult = (lr / (ld.Value));
                    if (countResult != null && countResult.HasValue)
                        record.TotalFinishedProgress = (countResult.Value * 100).ToString("F2") + "%";
                    else
                        record.TotalFinishedProgress = "0%";

                    result.Add(record);
                }
            }
            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="view"></param>
        /// <param name="details"></param>
        /// <returns></returns>
        public OperationResult Add(CulvertStatisticsView view)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            CulvertStatistics cs = new CulvertStatistics();
            cs = view.CopyTo<CulvertStatistics>();
            //保存涵洞
            if (CulvertStatisticsRepository.Insert(cs) > 0)
            {
                //保存涵洞明细
                string detailListJson = view.CulvertDetailListJson;
                if (!String.IsNullOrEmpty(detailListJson))
                {
                    List<CulvertStatisticsDetailView> detailViewList = JsonHelper.JsonDeserialize<List<CulvertStatisticsDetailView>>(detailListJson);
                    if (detailViewList != null && detailViewList.Count > 0)
                    {
                        List<CulvertStatisticsDetail> detailList = new List<CulvertStatisticsDetail>();
                        CulvertStatisticsDetail detail;
                        foreach (CulvertStatisticsDetailView item in detailViewList)
                        {
                            detail = new CulvertStatisticsDetail();
                            detail = item.CopyTo<CulvertStatisticsDetail>();
                            detail.ID = GuidHelper.NewGuid();
                            detailList.Add(detail);
                        }
                        if (detailList.Count > 0)
                        {
                            if (CulvertStatisticsDetailRepository.Insert(detailList) > 0)
                            {
                                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
                            }
                        }
                    }
                }
                result = new OperationResult(OperationResultType.Success, "保存记录成功");
            }
            return result;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="view"></param>
        /// <param name="details"></param>
        /// <returns></returns>
        public OperationResult Modify(CulvertStatisticsView view)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            CulvertStatistics cs = new CulvertStatistics();
            cs = view.CopyTo<CulvertStatistics>();
            //保存涵洞
            if (CulvertStatisticsRepository.Update(cs) >= 0)
            {
                //删除旧的涵洞明细
                var oldDetailList = CulvertStatisticsDetails.Where(m => m.CulvertStatisticsID == cs.ID);
                if (oldDetailList != null && oldDetailList.Count() > 0)
                {
                    CulvertStatisticsDetailRepository.Delete(oldDetailList);
                }

                //保存涵洞明细
                string detailListJson = view.CulvertDetailListJson;
                if (!String.IsNullOrEmpty(detailListJson))
                {
                    //json->对象（注：使用此方法，当为空时，可能转换出错）
                    List<CulvertStatisticsDetailView> detailViewList = JsonHelper.JsonDeserialize<List<CulvertStatisticsDetailView>>(detailListJson);
                    if (detailViewList != null && detailViewList.Count > 0)
                    {
                        List<CulvertStatisticsDetail> detailList = new List<CulvertStatisticsDetail>();
                        CulvertStatisticsDetail detail;
                        foreach (CulvertStatisticsDetailView item in detailViewList)
                        {
                            detail = new CulvertStatisticsDetail();
                            detail = item.CopyTo<CulvertStatisticsDetail>();
                            detailList.Add(detail);
                        }
                        if (detailList.Count > 0)
                        {
                            if (CulvertStatisticsDetailRepository.Insert(detailList) > 0)
                            {
                                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
                            }
                        }
                    }
                }
                result = new OperationResult(OperationResultType.Success, "保存记录和明细成功");
            }
            return result;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="culvertStatisticsView"></param>
        /// <param name="saveList"></param>
        /// <param name="isUpdateDetails"></param>
        public void Save(CulvertStatisticsView culvertStatisticsView, List<CulvertStatisticsDetailView> saveList, bool isUpdateDetails = true)
        {
            CulvertStatistics record = CulvertStatisticsRepository.Entities.FirstOrDefault(a => a.ID == culvertStatisticsView.ID);
            if (record != null)
            {
                Modify(culvertStatisticsView);
            }
            else
            {
                Add(culvertStatisticsView);
            }

            if (isUpdateDetails)
            {
                DeleteCulvertStatisticsDetails(culvertStatisticsView.ID);
                foreach (CulvertStatisticsDetailView bsd in saveList)
                {
                    InsertCulvertStatisticsDetail(bsd);
                }
            }
        }



        /// <summary>
        /// 清空涵洞对应的明细记录
        /// </summary>
        /// <param name="culvertStatisticsID"></param>
        private void DeleteCulvertStatisticsDetails(Guid culvertStatisticsID)
        {
            List<CulvertStatisticsDetail> lstCulvertStatisticsDetails = CulvertStatisticsDetailRepository.Entities.Where(a => a.CulvertStatisticsID == culvertStatisticsID).ToList();
            foreach (CulvertStatisticsDetail bsd in lstCulvertStatisticsDetails)
            {
                CulvertStatisticsDetailRepository.Delete(bsd.ID);
            }
        }

        /// <summary>
        /// 插入涵洞明细记录
        /// </summary>
        /// <param name="culvertStatisticsDetailView"></param>
        private void InsertCulvertStatisticsDetail(CulvertStatisticsDetailView culvertStatisticsDetailView)
        {
            CulvertStatisticsDetail record = new CulvertStatisticsDetail();
            record = culvertStatisticsDetailView.CopyTo<CulvertStatisticsDetail>();
            CulvertStatisticsDetailRepository.Insert(record);
        }

        /// <summary>
        /// 获取涵洞信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public CulvertStatisticsView GetCulvert(Guid id)
        {
            CulvertStatisticsView result = new CulvertStatisticsView();
            var culvert = CulvertStatisticses.FirstOrDefault(m => m.ID == id);
            if (culvert != null)
            {
                result = culvert.CopyTo<CulvertStatisticsView>();
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperationResult Delete(Guid id)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            if (id != null && !id.Equals(Guid.Empty))
            {
                try
                {
                    //查找子记录并删除
                    var detailList = CulvertStatisticsDetails.Where(m => m.CulvertStatisticsID == id);
                    if (detailList != null && detailList.Count() > 0)
                    {
                        CulvertStatisticsDetailRepository.Delete(detailList);
                    }

                    //查找主记录并删除
                    var culvert = CulvertStatisticses.FirstOrDefault(m => m.ID == id);
                    if (culvert != null)
                    {
                        if (CulvertStatisticsRepository.Delete(culvert) > 0)
                        {
                            result = new OperationResult(OperationResultType.Success, "删除成功");
                        }
                    }
                }
                catch (Exception ex)
                {
                    result = new OperationResult(OperationResultType.Error, ex.Message);
                }
            }
            return result;
        }
    }
}
